package com.easylinkin.linkappapi.lobar.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.lobar.entity.LaborCompany;
import com.easylinkin.linkappapi.lobar.entity.LaborCompanyProject;
import com.easylinkin.linkappapi.lobar.entity.emp.EmpUserBase;
import com.easylinkin.linkappapi.lobar.mapper.EmpUserBaseMapper;
import com.easylinkin.linkappapi.lobar.mapper.LaborCompanyMapper;
import com.easylinkin.linkappapi.lobar.mapper.LaborCompanyProjectMapper;
import com.easylinkin.linkappapi.lobar.service.LaborCompanyProjectService;
import com.easylinkin.linkappapi.lobar.service.LaborCompanyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 劳务公司表 服务实现类
 * </p>
 *
 * @author kanyuanfeng
 * @since 2022-04-13
 */
@Service
public class LaborCompanyServiceImpl extends ServiceImpl<LaborCompanyMapper, LaborCompany> implements LaborCompanyService {

  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;
  @Autowired
  private LaborCompanyProjectService laborCompanyProjectService;
  @Autowired
  private EmpUserBaseMapper empUserBaseMapper;
  @Autowired
  private LaborCompanyProjectMapper laborCompanyProjectMapper;

  /**
   * 增加
   * @param laborCompany
   */
  @Override
  public void insert(LaborCompany laborCompany) {
//    /**
//     * 验证重复
//     */
//    this.checkExist(laborCompany);
    //是否前端传过来id
    if (StringUtils.isBlank(laborCompany.getId()) && StringUtils.isNotBlank(laborCompany.getCode())){
      //查看code是否存在
      LaborCompany company = this.findByCode(laborCompany.getCode());
      if (null != company){
        laborCompany.setId(company.getId());
      }
    }

    this.checkAddExist(laborCompany);
    //设置基本属性
    this.setBase(laborCompany);
    if (StringUtils.isNotBlank(laborCompany.getId())){
      baseMapper.updateById(laborCompany);
    }else {
      this.save(laborCompany);
    }
    //绑定到项目上
    LaborCompanyProject laborCompanyProject = new LaborCompanyProject();
    Set<String> ids = new HashSet<>();
    ids.add(laborCompany.getId());
    laborCompanyProject.setCompanyName(laborCompany.getName());
    laborCompanyProject.setIds(ids);
    laborCompanyProjectService.insert(laborCompanyProject);
  }

  /**
   * 增加
   * @param laborCompany
   */
  @Override
  public void insertOne(LaborCompany laborCompany) {
    /**
     * 验证重复
     */
    this.checkExist(laborCompany);
    laborCompany.setModifyTime(new Date());
    laborCompany.setCreateTime(new Date());
    this.save(laborCompany);
    //更新下面对应的user 单位id
    UpdateWrapper<EmpUserBase> updateWrapper = new UpdateWrapper<>();
    updateWrapper.set("company_id_",laborCompany.getId())
        .eq("company_id_",laborCompany.getCode());
    empUserBaseMapper.update(null,updateWrapper);
  }

  /**
   * 根据id编辑
   * @param laborCompany
   */
  @Override
  public void updateOne(LaborCompany laborCompany) {
    /**
     * 验证重复
     */
    this.checkExist(laborCompany);
    //设置基本属性
    this.setBase(laborCompany);
    this.updateById(laborCompany);
  }

  /**
   * @Description: 根据条件，查询劳务公司
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @Override
  public List<LaborCompany> queryCompanyList() {
    List<LaborCompany> companyList = baseMapper.selectList(new QueryWrapper<>());
    return companyList;
  }

  /**
   * @Description: 根据code查询劳务公司详情
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @Override
  public LaborCompany findByCode(String code) {
    QueryWrapper<LaborCompany> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("code_",code);
    List<LaborCompany> laborCompanies = baseMapper.selectList(queryWrapper);
    if (laborCompanies.size() > 0){
      return laborCompanies.get(0);
    }
    return null;
  }

  @Override
  public IPage<LaborCompany> queryListByPage(RequestModel<LaborCompany> requestModel) {
    Page page = requestModel.getPage();
    LaborCompany laborCompany = requestModel.getCustomQueryParams();
    //项目id 过滤
    laborCompany.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    IPage<LaborCompany> laborCompanyIPage = baseMapper.queryListByPage(page, laborCompany);
    return laborCompanyIPage;
  }

  /**
   * 验证重复
   */
  private void checkExist(LaborCompany laborCompany) {
    QueryWrapper<LaborCompany> queryWrapper = new QueryWrapper<>();
    //设置判断重复条件
    queryWrapper.and(qr->
      qr.eq("name_",laborCompany.getName()).or().eq("code_",laborCompany.getCode())
    );
    //编辑的时候存在id
    Optional.ofNullable(laborCompany.getId()).ifPresent(id -> queryWrapper.ne("id",laborCompany.getId()));
    Integer integer = baseMapper.selectCount(queryWrapper);
    if (integer>0){
      throw new BusinessException("该劳务公司名称或统一社会信用代码重复");
    }
  }

  /**
   * 验证重复
   */
  private void checkAddExist(LaborCompany laborCompany) {
    QueryWrapper<LaborCompanyProject> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("company_id_",laborCompany.getId())
        .eq("tenant_id_",linkappUserContextProducer.getNotNullCurrent().getTenantId())
        .eq("delete_state_",1);
    List<LaborCompanyProject> companyProjects = laborCompanyProjectMapper
        .selectList(queryWrapper);
    if (companyProjects.size() > 0){
      throw new BusinessException("该劳务公司已经在本项目中存在");
    }
  }

  /**
   * 设置基本属性
   * @param laborCompany
   */
  private void setBase(LaborCompany laborCompany) {
    laborCompany.setModifyTime(new Date());
    laborCompany.setModifyId(linkappUserContextProducer.getCurrent().getId());
    //没有id就是新增,有就是编辑
    if (StringUtils.isBlank(laborCompany.getId())){
      laborCompany.setCreatorId(linkappUserContextProducer.getCurrent().getId());
      laborCompany.setCreateTime(new Date());
      laborCompany.setCreateTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    }
  }
}
